package com.lhj.bootdemo.controller;

import com.lhj.bootdemo.entity.Student;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author lhj
 * @version 1.0
 * @date 2022/5/26 10:07 上午
 * @description:
 */

@Slf4j
@RestController
public class RedisOptController {

    @Autowired
    StringRedisTemplate stringRedisTemplate; //操作kv都是字符串

    @Autowired
    RedisTemplate redisTemplate;// kv都是对象的


    @Autowired
    RedisTemplate myRedisTemplate;


    @ApiOperation(value = "redis字符串存储")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = String.class)})
    @PostMapping("/testRedisStrSave")
    public String testRedisStrSave(@RequestBody Map map) {
        String index = (String) map.get("index");
        stringRedisTemplate.opsForValue().append("index", index);
        return "redis字符串存储ok";
    }


    @ApiOperation(value = "redis对象存储")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = String.class)})
    @PostMapping("/testRedisObjSave")
    public String testRedisObjSave(@RequestBody Map map) {
        String index = (String) map.get("index");
        Student student = new Student("xiatian", "天津", 22, index);
        myRedisTemplate.opsForValue().set("student", student);
        return "redis对象存储ok";
    }


    @ApiOperation(value = "redis的SessionCallback的使用")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = String.class)})
    @PostMapping("/testRedisSessionCallback")
    public String testRedisSessionCallback(@RequestBody Map map) {
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                redisOperations.opsForValue().set("w", "wu");
                redisOperations.opsForValue().set("w1", "wu1");
                return null;
            }
        });
        return "redis对象存储ok";
    }


}
